package com.why.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;

public class ExcelRead {

    public static JSONArray excelRead(String excelPath){
        JSONArray result = new JSONArray();
        FileInputStream xlsStream = null;
        ArrayList<String> content = new ArrayList<String>();
        try{
            xlsStream = new FileInputStream(new File(excelPath));
            Workbook workbook = new XSSFWorkbook(xlsStream);
            Sheet sheetAt = workbook.getSheetAt(0);
            int rows = sheetAt.getPhysicalNumberOfRows();
            content = getContent(sheetAt.getRow(0));
            for (int i = 1; i < rows; i++) {
                result.add(getJSON(sheetAt.getRow(i),content));
            }
        }catch (Exception e){

        }

        return result;
    }

    private static ArrayList<String> getContent(Row row) {
        ArrayList<String> content = new ArrayList<String>();
        int num = row.getPhysicalNumberOfCells();
        for (int i = 0; i < num; i++) {
            content.add(row.getCell(i).toString());
        }
        return content;
    }

    private static JSONObject getJSON(Row row,ArrayList<String> content){
        JSONObject result = new JSONObject();
        for(int i = 0; i< content.size(); i++){
            result.put(content.get(i),row.getCell(i).toString());
        }
        return result;
    }

    public static void main(String[] args) {
        String excelPath = "./user.xlsx";
        JSONArray  ja = excelRead(excelPath);
        System.out.println(ja);
    }

}
